package com.example.esstudy.controller;

import com.example.esstudy.model.Book;
import com.example.esstudy.repo.BookRepo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shuc001
 * @Date 2018/9/6 下午4:58
 *
 *
 * 项目启动后 会自动创建索引 需要@Document注解,建议使用json的配置方式
 */
@RestController
public class BookController {


    @Autowired
    private BookRepo bookRepo;

    @Autowired
    private TransportClient client;



    @GetMapping("/book/find")
    public String findOne(){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(
                QueryBuilders.termQuery("author","束畅").boost(2.0f)
        );
        boolQuery.should(
                QueryBuilders.matchQuery("name","java")
        );
        Iterable<Book> search = bookRepo.search(boolQuery);
        return "ojbk";
    }

    @GetMapping("/book/terms")
    public String aggs(){
        SearchResponse searchResponse = client.prepareSearch("book").setTypes("doc").
                addAggregation(AggregationBuilders.terms("coutnagg").field("tags")).get();
        Terms terms = searchResponse.getAggregations().get("coutnagg");
        for (Terms.Bucket bucket : terms.getBuckets()) {
            System.out.println(bucket.getKey()+":"+bucket.getDocCount());
        }
        return "ojbk";
    }

    @GetMapping("/book/min")
    public String min(){
        SearchResponse searchResponse = client.prepareSearch("book").setTypes("doc").
                addAggregation(AggregationBuilders.min("minagg").field("price")).
                get();
        Min m = searchResponse.getAggregations().get("minagg");
        System.out.println(m.getValue());
        return "ok";
    }

    @GetMapping("/book/qa")
    public String qa(){
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.termQuery("author","束畅"));
        SearchResponse searchResponse = client.prepareSearch("book").setTypes("doc").
                setQuery(bqb).addAggregation(AggregationBuilders.min("minagg").field("price"))
                .highlighter(new HighlightBuilder().field("author").preTags("<font color='red'>").postTags("</font>")).get();
        System.out.println(searchResponse);

        for (SearchHit fields : searchResponse.getHits()) {
            for (Text text : fields.getHighlightFields().get("author").getFragments()) {
                System.out.println(text);
            }
        }
        return "ok";
    }

    @GetMapping("/book/max")
    public String max(){
        SearchResponse searchResponse = client.prepareSearch("book").setTypes("doc").addAggregation(AggregationBuilders.max("max").field("price")).get();
        Max m = searchResponse.getAggregations().get("max");
        System.out.println(m.getValue());
        return "ok";
    }


    @GetMapping("/book/avg")
    public void avg(){
        SearchResponse searchResponse = client.prepareSearch("book").setTypes("doc").addAggregation(AggregationBuilders.avg("priceAvg").field("price")).setSize(0).get();
        Avg a  = searchResponse.getAggregations().get("priceAvg");
        System.out.println(a.getValue());
    }

    @GetMapping("/book/save")
    public String saveOne(){
        Book book = new Book();
        book.setDesc("java入门必备");
        book.setAuthor("束畅");
        book.setName("java从入门到放弃");
        book.setId("2");
        book.setAddress("机械工业出版社");
        book.setPrice(new Float(14.58));
        book.setPublishTime(LocalDate.now().toString());
        List<String> tags = new ArrayList<>();
        tags.add("放弃");
        tags.add("挣钱");
        book.setTags(tags);
        bookRepo.save(book);
        return "ok";
    }


    @GetMapping("book/demo")
    public String getDemo(){
        ValueCountAggregationBuilder field = AggregationBuilders.count("bc").field("tags");
        SearchResponse response = client.prepareSearch("book").addAggregation(field).execute().actionGet();
        Terms bc = response.getAggregations().get("bc");
        System.out.println(bc.getBuckets());
        return "ok";
    }

}
